package com.dhy.socket.request.util;

import com.dhy.socket.request.core.DhyHttpRequest;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 大忽悠
 * @create 2022/6/20 17:38
 */
public class RawRequestParse {
    private static final String URL_PARAM_SEPARATOR = "\\?";
    private static final String PARAM_SEPARATOR = "&";
    private static final String KEY_VAL_SEPARATOR = "=";

    /**
     * 解析请求行
     */
    public static DhyHttpRequest parseHttpRequest(HttpRequest httpRequest) {
        String httpMethod = httpRequest.method().toString();
        String[] splits = httpRequest.uri().split(URL_PARAM_SEPARATOR);
        String uri = splits[0];
        DhyHttpRequest.DhyHttpRequestBuilder builder = DhyHttpRequest.builder().method(httpMethod).url(uri);
        //如果请求路径上存在参数,就解析
        if (splits.length > 1) {
                builder.params(resolveParam(splits[1]));
        }
        return builder.build();
    }

    /**
     * 解析请求体中的请求参数--->name=dhy&age=18
     */
    public static void parseHttpContent(DhyHttpRequest request,HttpContent httpContent){
        ByteBuf dataBuf = httpContent.content();
        int capacity = dataBuf.capacity();
        if(capacity==0){
            return;
        }
        byte[] data = new byte[capacity];
        dataBuf.readBytes(data);
        Map<String, String> params = request.getParams();
        Map<String, String> bodyParams = RawRequestParse.resolveParam(new String(data));
        if(params!=null){
            request.getParams().putAll(bodyParams);
        }else {
            request.setParams(bodyParams);
        }
    }

    /**
     * 解析: name=dhy&age=18这样的请求参数字符串
     */
    private static Map<String, String> resolveParam(String keyVals)  {
        HashMap<String, String> paramMap = new HashMap<>();
        try{
            String[] params = keyVals.split(PARAM_SEPARATOR);
            for (String param : params) {
                String[] keyVal = param.split(KEY_VAL_SEPARATOR);
                String key = URLDecoder.decode(keyVal[0], "utf-8");
                String val = URLDecoder.decode(keyVal[1], "utf-8");
                paramMap.put(key, val);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return paramMap;
    }
}
